package com.apexsoft.assets.base.convert;


import com.apexsoft.assets.base.utils.ValidateUtil;
import org.springframework.cglib.core.Converter;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;

@Component
public class ParseDateConverter implements Converter {

    //日期转换格式
    private String pattern = "yyyy-MM-dd HH:mm:ss";
    private SimpleDateFormat sdf = null;

    public ParseDateConverter() {
        sdf = new SimpleDateFormat(pattern);
    }

    public ParseDateConverter(String pattern) {
        this.pattern = pattern;
        sdf = new SimpleDateFormat(pattern);
    }

    public void setPattern(String pattern){
        this.pattern = pattern;
        sdf = new SimpleDateFormat(pattern);
    }

    @Override
    // value 源对象属性，target 目标对象属性类，context 目标对象setter方法名
    public Object convert(Object value, Class target, Object context) {
        if(value instanceof String){
            if (target != String.class){
                ValidateUtil.isDate((String)value,pattern);
                try{
                        return sdf.parse((String)value);
                }catch (Exception e){
                }
            }
        }
        return value;
    }

}
